using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PiggyBankCashFlowApi.Delegate.command;

namespace PiggyBankCashFlowApi.Controllers;

[ApiController]
[Route("api/v1/piggy-bank/cash-flows")]
public class CashFlowController(ILogger<CashFlowController> logger, IMediator mediator)
    : ControllerBase
{
    [HttpGet("hello-world", Name = "TestIsServerUp")]
    public async Task<IActionResult> TestIsServerUp()
    {
        await Task.Delay(300);
        return Ok("hello world!");
    }


    [HttpPost(Name = "CreateCashFlow")]
    [Authorize("UserAccess")]
    public async Task<IActionResult> Create([FromBody] CreateCashFlowCommand command)
    {
        var entity = await mediator.Send(command);
        return CreatedAtRoute("GetCashFlowById", new { id = entity.Id }, entity);
    }

    [HttpDelete("{id:int}", Name = "DeleteCashFlowById")]
    [Authorize("UserAccess")]
    public async Task<IActionResult> Delete([FromRoute] int id)
    {
         await mediator.Send(new DeleteCashFlowCommand(id));
         return Ok();
    }

    [HttpGet("{id:int}", Name = "GetCashFlowById")]
    public async Task<IActionResult> Get([FromRoute] int id)
    {
        return Ok(await mediator.Send(new QueryCashFlowByIdCommand(id)));
    }


    [HttpGet("by-users/", Name = "GetCashFlowByUserIds")]
    public async Task<IActionResult> GetByUserId([FromQuery] int[] userIds, [FromQuery] int page,
        [FromQuery] int pageSize)
    {
        return Ok(await mediator.Send(new QueryByUserIdAndPageCommand(userIds, page, pageSize)));
    }


    [HttpPatch(Name = "UpdateCashFlow")]
    [Authorize("UserAccess")]
    public async Task<IActionResult> Update([FromBody] UpdateCashFlowCommand command)
    {
        return Ok(await mediator.Send(command));
    }
}